package com.tsd.system.controller;

import com.alibaba.fastjson.JSON;
import com.tsd.core.constants.Constants;
import com.tsd.core.shiro.helper.ShiroAuthorizationInfoHelper;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.ErrorCode;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.HttpResult;
import com.tsd.core.vo.PageBean;
import com.tsd.system.entity.SysResource;
import com.tsd.system.entity.SysResourceExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.service.SysResourceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：SysResource 控制层
 *
 * @author Hillpool
 * @date 2019/03/12 12:20:51
 */
@Controller
@Scope("prototype")
@RequestMapping("/api/v2")
public class SysResourceController extends SystemBaseController {

    private final SysResourceService sysResourceService;

    @Autowired
    public SysResourceController(SysResourceService sysResourceService) {
        this.sysResourceService = sysResourceService;
    }

    @ApiOperation(value = "根据id获取系统资源信息")
    @ResponseBody
    @RequestMapping(value = "/getSysResourceById.action", method = RequestMethod.POST)
    public HttpResult<SysResource> getSysResourceById() {
        HttpResult<SysResource> hr = new HttpResult<SysResource>();
        try {
            Map<String, Object> map = super.getParams(request);
            Long id = (Long) map.get("id");
            super.checkEmpty(id, "请提供参数id");
            SysResource sysResource = sysResourceService.getSysResourceById(id);
            hr.setData(sysResource);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "保存系统资源信息")
    @ResponseBody
    @RequestMapping(value = "/saveSysResource.action", method = RequestMethod.POST)
    public HttpResult<String> saveSysResource() {
        HttpResult<String> hr = new HttpResult<String>();
        try {
            Map<String, Object> map = super.getParams(request);
            SysUser sysUser = this.getSysUser();
            SysResource t = JSON.parseObject(JSON.toJSONString(map), SysResource.class);
            if (SysResourceExt.RES_TYPE_APPLICATION.equals(t.getRes_type()) &&
                    !HlpUtils.isEmpty(t.getParent_sid(), Constants.ROOT_PARENT_SID) ||
                    !SysResourceExt.RES_TYPE_APPLICATION.equals(t.getRes_type()) &&
                            HlpUtils.isEmpty(t.getParent_sid(), Constants.ROOT_PARENT_SID)) {
                throw new HlpException("应用必须设置为第一级");
            }
            sysResourceService.saveSysResource(t, sysUser);
            ShiroAuthorizationInfoHelper.clearCache();
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "根据id删除系统资源信息")
    @ResponseBody
    @RequestMapping(value = "/deleteSysResource.action", method = RequestMethod.POST)
    public HttpResult<String> deleteSysResource() {
        HttpResult<String> hr = new HttpResult<String>();
        try {
            SysUser sysUser = this.getSysUser();
            Map<String, Object> map = super.getParams(request);
            Long id = HlpUtils.getLong(map, "id");
            super.checkEmpty(id, "请提供参数id");
            sysResourceService.deleteSysResource(id, sysUser);
            ShiroAuthorizationInfoHelper.clearCache();
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "分页查询系统资源信息")
    @ResponseBody
    @RequestMapping(value = "/findSysResources.action", method = RequestMethod.POST)
    public HttpResult<List<SysResourceExt>> findSysResources() {
        HttpResult<List<SysResourceExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = super.getParams(request);
            Map<String, Object> params = new HashMap<String, Object>();
            Integer dr = HlpUtils.getInteger(map, "dr");
            String searchValue = HlpUtils.getString(map, "searchValue");
            HlpUtils.copyStringValue(map, params, "parent_sid", "parent_sid", false, false);
            if (!HlpUtils.isEmpty(dr) && dr != -1) {
                params.put("dr", dr);
            }
            if (!HlpUtils.isEmpty(searchValue)) {
                params.put("searchValue", "%" + searchValue + "%");
            }
            PageBean page = new PageBean(map);
            List<SysResourceExt> list = sysResourceService.findSysResources(params, page);
            hr.setData(list);
            hr.setPage(page);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "查询系统资源树")
    @ResponseBody
    @RequestMapping(value = "/findSysResourceTree.action", method = RequestMethod.POST)
    public HttpResult<List<SysResourceExt>> findSysResourceTree() throws Exception {
        HttpResult<List<SysResourceExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = this.getParams(request);
            String parentId = HlpUtils.getString(map, "parentId");
            if (HlpUtils.isEmpty(parentId)) {
                parentId = Constants.ROOT_PARENT_SID;
            }
            List<SysResourceExt> list = sysResourceService.findSysResourceTree(parentId);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "查询某个角色拥有的系统资源树")
    @ResponseBody
    @RequestMapping(value = "/findSysResourceTreeByRole.action", method = RequestMethod.POST)
    public HttpResult<List<SysResourceExt>> findSysResourceTreeByRole() throws Exception {
        HttpResult<List<SysResourceExt>> hr = new HttpResult<>();
        try {
            Map<String, Object> map = this.getParams(request);
            String roleSid = HlpUtils.getString(map, "roleSid", true, "roleSid不能为空");
            List<SysResourceExt> list = sysResourceService.findSysResourceTreeByRole(roleSid, null);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "移动资源")
    @ResponseBody
    @RequestMapping(value = "/changeResourceParentId.action", method = RequestMethod.POST)
    public HttpResult<String> changeResourceParentId() {
        HttpResult<String> hr = new HttpResult<String>();
        try {
            Map<String, Object> map = super.getParams(request);
            String ids = HlpUtils.getString(map, "ids");
            String newParentId = HlpUtils.getString(map, "newParentId");
            super.checkEmpty(ids, "请提供参数ids");
            super.checkEmpty(newParentId, "请提供参数newParentId");
            SysUser opUser = this.getSysUser();
            List<String> idList = JSON.parseArray(ids, String.class);
            if (idList == null || idList.isEmpty()) {
                throw new HlpException("请选择资源");
            }
            for (String id : idList) {
                sysResourceService.updateSysResouceParentId(id, newParentId, opUser);
            }
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

    @ApiOperation(value = "查询当前用户授权访问的系统")
    @ResponseBody
    @RequestMapping(value = "/queryAllApplications4User.action", method = RequestMethod.POST)
    public HttpResult<Object> queryAllApplications4User() {
        HttpResult<Object> hr = new HttpResult<Object>();
        try {
            SysUser opUser = super.getSysUser();
            List<SysResourceExt> list = sysResourceService.queryValidApps(opUser);
            hr.setData(list);
            hr.setCode(ErrorCode.CODE_SUCCESS);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }
}
